var userAdminWindows = new Array();

function getUserColumnModel(sm) {
	return [sm,{
			header: _('User'),
			readOnly: true,
			dataIndex: 'UserId',
			hidden: false
		},{
			header: _('Name'),
			readOnly: true,
			dataIndex: 'name',
			hidden: false
		},{
			header: _('Profile'),
			readOnly: true,
			dataIndex: 'GroupId',
			renderer: translate,
			hidden: false
		},{
			header: _('Team'),
			readOnly: true,
			dataIndex: 'TeamText',
			hidden: false
		},{
			header: _('Status'),
			readOnly: true,
			dataIndex: 'StatusId',
			renderer: translate,
			hidden: false
		},{
			header: _('Last Login'),
			readOnly: true,
			dataIndex: 'lastLogin',
			renderer: renderUserDate,
			hidden: false
		}];
}
MyDesktop.UserAdmin = Ext.extend(Ext.app.Module, {

    init : function(){
        this.launcher = {
            text: _('User Administration'),
            iconCls: 'users',
            handler : this.createWindow,
            windowId : 'UserAdmin',
            scope: this
        }
    },

    createColumnModel: function(sm) {
		return new Ext.grid.ColumnModel(getUserColumnModel(sm));    	
    },
    requestList: function(src) {
    	var desktop = src.desktop;
        var winname = "accountRequest";
        var win = desktop.getWindow(winname);
		
        if(!win){
	        var ds = new Ext.data.JsonStore({
	            url: getMainUrl(),
	            method: 'POST',
	            baseParams: {action: 'user_admin', op: 'accreq'},
	            autoLoad: false,
	            root: 'results',
	            id: 'id',
	            fields:[
	                {name: 'mail', mapping: 'extra'},
	                {name: 'teamid'},
	                {name: 'status'},
	                {name: 'statusmsg'},
	                {name: 'teamname'},
	                {name: 'date', mapping: 'expire'}
	            ]
	        });
			
			var sm = new Ext.grid.CheckboxSelectionModel(
			);
			
			var cm = new Ext.grid.ColumnModel(
						[sm,{
							header: _('e-mail'),
							readOnly: true,
							dataIndex: 'mail',
							hidden: false
						},{
							header: _('Date'),
							readOnly: true,
							dataIndex: 'date',
							renderer: renderUserDate,
							hidden: false
						},{
							header: _('Status'),
							readOnly: true,
							dataIndex: 'statusmsg',
							hidden: false
						},{
							header: _('Team'),
							readOnly: true,
							dataIndex: 'teamname',
							hidden: true
						}]
					); 
			
			cm.defaultSortable = true;

			var filters = new Ext.ux.grid.GridFilters({
					menuFilterText: _('Filter'),
					filters:[
					{type: 'string',  dataIndex: 'statusmsg'}
					],
					local: true
			});
						
			var grid = new Ext.grid.GridPanel({
				id: 'userAdminRequestGrid',
				autoExpandColumn: 1,
				loadMask: {msg: _('Loading...')},
				store: ds,
				cm: cm,
				selModel: sm,
				plugins: filters,
				tbar: [{
					text: _('Send'),
					tooltip: _('Send invitation'),
					iconCls: 'send',
					handler: function () {
							if (grid.selModel.getCount()>0) {
								var selections = grid.selModel.getSelections();
							  	var prez = [];
							  	for(i = 0; i< grid.selModel.getCount(); i++){
							  		//if (selections[i].data.status==0) {
							  			prez.push(selections[i].id);
							  		//}
							  	}
							  	var encoded_array = Ext.encode(prez);

							  	var util = new Verbum.Utilities();
								util.request({
									el: grid.getEl(),
						            params: { 
						               action: "user_admin", 
						               ids:  encoded_array,
						               op: 'newm'
						              }											
								});

								util.on({
									'done': function() {
										ds.reload();
									}
								});				
							
							} else {
								Ext.Msg.message(_('Please, select an item from the list.'));
							}

						}
				},{
					text: _('Remove'),
					iconCls: 'remove',
					handler: function () {
							if (grid.selModel.getCount()>0) {
								var selections = grid.selModel.getSelections();
							  	var prez = [];
							  	for(i = 0; i< grid.selModel.getCount(); i++){
						  			prez.push(selections[i].id);
							  	}
							  	var encoded_array = Ext.encode(prez);

							  	var util = new Verbum.Utilities();
								util.request({
									el: grid.getEl(),
						            params: { 
						               action: "user_admin", 
						               ids:  encoded_array,
						               op: 'rmr'
						              }											
								});

								util.on({
									'done': function() {
										ds.reload();
									}
								});				
							
							} else {
								Ext.Msg.message(_('Please, select an item from the list.'));
							}

						}
				},'-',
				{
					xtype:'button',
					tooltip: _('Refresh'),
					iconCls: "x-tbar-loading",
					handler: function() {
						ds.reload();	
					}
				}		
				]	
			});

            win = desktop.createWindow({
				id: winname,
				title: _('Requests'),
				closable:true,
				width:550,
				height:350,
				plain:true,
				layout: 'fit',
				iconCls: 'add',
				items: grid
            });
			
            ds.load();

        }
          
        win.show();    	
    },
    
    createWindow : function(src){
        var desktop = this.app.getDesktop();
        var winname = "userAdminWin";
        var win = desktop.getWindow(winname);
		var pnt = this;
		
        if(!win){
			var ds = new Ext.data.Store({
				proxy: new Ext.data.HttpProxy({
					url: getMainUrl(),
					method: 'POST'
					}),
					baseParams: {action: 'user_admin'},
				reader: new Ext.data.JsonReader({
						root: 'results',
						id: 'id'
					},[
					{name: 'UserId',type:'string',mapping:'userid'},
					{name: 'name',type:'string',mapping:'name'},
					{name: 'GroupId',type:'string',mapping:'groupid'},
					{name: 'TeamId',type:'string',mapping:'teamid'},
					{name: 'StatusId',type:'string',mapping:'status'},
					{name: 'TeamText',type:'string',mapping:'teamname'},
					{name: 'lastLogin',type:'string',mapping: 'lastlogin'}
					]),
					sortInfo: {field: 'UserId',direction:'ASC'}
			});
			
			var sm = new Ext.grid.CheckboxSelectionModel(
			);
			
			var view = new Ext.grid.GridView({
				autoFill: true,
   		    	getRowClass : function (row, index) { 
			      var cls = ''; 
			      var data = row.data; 
			      switch (data.StatusId) { 
			         case 'INACTIVE' : 
			            cls = 'red-row' 
			            break; 
			      } 
			      return cls; 
			   } 
			});
			
			var cm = this.createColumnModel(sm);
			cm.defaultSortable = true;

			var filters = new Ext.ux.grid.GridFilters({
					menuFilterText: _('Filter'),
					filters:[
					{type: 'string',  dataIndex: 'UserId', fieldName: 'userId'},
					{type: 'string',  dataIndex: 'GroupId', fieldName: 'group'},
					{type: 'string',  dataIndex: 'TeamText'},
					{type: 'list',  
					dataIndex: 'StatusId', 
					options: [
						{id: 'ACTIVE', text: translate('ACTIVE')},
						{id: 'INACTIVE', text: translate('INACTIVE')}]
					}],
					local: true
			});
						
			var grid = new Ext.grid.GridPanel({
				id: 'userAdmGrid',
				autoExpandColumn: 1,
				loadMask: {msg: _('Loading...')},
				store: ds,
				cm: cm,
				selModel: sm,
				view: view,
				plugins: filters,
				bbar: new Ext.StatusBar({
		            iconCls: 'hint',
		            text: _('Hint:') + ' ' + _('Double click on a row to edit it')
	        	}),
				tbar: [{
					text: _('Enable/Disable'),
					tooltip: _('Enable/Disable the selected elements'),
					iconCls: 'toggle',
					handler: function () {
							if (grid.selModel.getCount()>0) {
								var selections = grid.selModel.getSelections();
							  	var prez = [];
							  	for(i = 0; i< grid.selModel.getCount(); i++){
									prez.push(selections[i].json.userid);
							  	}
							  	var encoded_array = Ext.encode(prez);

								lMask = new Ext.LoadMask(grid.getEl(), {msg: _('Saving...'), removeMask: true});
						    	lMask.show();

								Ext.Ajax.request({ 
								            waitMsg: _('Please wait...'),
								            url: getMainUrl(), 
								            params: { 
								               action: "user_admin", 
								               ids:  encoded_array,
								               op: 'toggle'
								              }, 
								            success: function(response){
								            	obj = Ext.util.JSON.decode(response.responseText);
								            	if (obj.success==false) {
								            		Ext.Msg.alert(_('Error'), obj.error);
								            	} else {
								            		ds.reload();	
								            	}
								            },
											callback: function ( options, success, response ) { 
												lMask.hide();
											}
							   });								
							} else {
								Ext.Msg.message(_('Please, select an item from the list.'));
							}

						}
				},'-',{
					text: _('New User'),
					tooltip: _('Send a new user invitation'),
					iconCls: 'add',
					handler: function() {
							Ext.Msg.show({
								title: _('New User'),
								msg: _('Enter an e-mail address. The user will receive a link to create an account.'),
								icon: Ext.Msg.QUESTION,
								prompt: true,
								buttons: {ok: _('Send'), cancel: _('Cancel')},
								fn: function(btn,text) {

									if (btn=="ok") {
										Ext.Ajax.request({ 
										            waitMsg: _('Please wait...'),
										            url: getMainUrl(), 
										            params: { 
										               action: "user_admin", 
										               mail: text,
										               op: 'new'
										              }, 
										            success: function(response){
										            	obj = Ext.util.JSON.decode(response.responseText);
										            	if (obj.success==false) {
										            		Ext.Msg.alert(_('Error'), obj.error);
										            	} else {
										            		Ext.Msg.message(_('The invitation was sent successfully!'));
										            	}
										            }
									   });
									}
								}
							})							

						}
				},{
					text: _('Requests'),
					tooltip: _('Applications for consideration'),
					iconCls: 'users',
					handler: function() {
							pnt.requestList({desktop: desktop });
						}
				},'-',
				{
					xtype:'button',
					tooltip: _('Refresh'),
					iconCls: "x-tbar-loading",
					handler: function() {
						ds.reload();	
					}
				},'-',{
					text: _('Send PM'),
					tooltip: _('Send a message'),
					iconCls: 'mail',
					handler: function sendMessage() {
						if (grid.selModel.getCount()>0) {
							var selections = grid.selModel.getSelections();
						  	var prez = [];
						  	for(i = 0; i< grid.selModel.getCount(); i++){
								prez.push(selections[i].json.userid);
						  	}
						  	var encoded_array = Ext.encode(prez);
							
						    var mForm = new Ext.form.FormPanel({
						        baseCls: 'x-plain',
						        url:getMainUrl(),
						        baseParams: {action: 'message', op: 'user'},
						        defaultType: 'textfield',
						        buttonAlign:'right',
						        waitMsgTarget: true,
						        bbar: new Ext.Toolbar({
												items:['->',
													{
														xtype:'button',
														tooltip: _('Cancel'),
														iconCls: 'cancel',
														text: _('Cancel'),
														handler: function() {
															mWin.close();
														}
													},
													{
														xtype:'button',
														tooltip: _('Send'),
														iconCls: 'send',
														text: _('Send'),
														handler: function() {
															if (mForm.getForm().isValid()) {
												                    mForm.getForm().submit({ 
												                        method:'POST', 
												                        waitMsg: _('Sending...'),
												 						
												                        success:function(form, action){
												                        	obj = Ext.util.JSON.decode(action.response.responseText);
												                        	Ext.Msg.message(obj.ret);
												                        	mWin.close();
												                        },
												 
												                        failure:function(form, action){ 
											                                obj = Ext.util.JSON.decode(action.response.responseText); 
											                                Ext.Msg.error(obj.error); 
												                        } 
												                    });								
															}
														}
													}
												 ]		
											}),
						        autoWidth: true,
						        autoHeight: true,
						        defaults: {msgTarget:'side', allowBlank: false, anchor: '95%'},
						        monitorResize: true,
						        items: [{
						            fieldLabel: _('Subject'),
						            name: 'subject',
						            id: 'subject',
						            selectOnFocus: true,
						        },{
						            hideLabel: true,
						            name: 'text',
						            xtype: 'textarea',
						            selectOnFocus: true,
						            height: 120
						        },{
						            name: 'ids',
						            xtype: 'hidden',
						            value: encoded_array
						        }]
						    });
						
						    var mWin = desktop.createWindow({
						        title: _('Send PM'),
						        width: 450,
						        minWidth: 450,
						        minHeight: 250,
						        layout: 'fit',
						        bodyStyle:'padding:5px;',
						        items: mForm,
								resizable: false,
								closable: true,
								draggable: true,
								iconCls: 'mail'
						    });
						
						    mWin.show();
						    focus(mForm,'subject');							

						} else {
							Ext.Msg.message(_('Please, select an item from the list.'));
						}						
					}
				},'-',this.addReset()]	
			});

            win = desktop.createWindow({
				id: winname,
				title: src.text,
				closable:true,
				width:550,
				height:350,
				plain:true,
				layout: 'fit',
				iconCls: 'users',
				items: grid
            });

			win.on({
				'close': {
					fn: function() {
						for (i=0;i<userAdminWindows.length;i++) {
							Ext.destroy(userAdminWindows[i]);	
						}
					}
				}
			});
			
			grid.on({
				'rowdblclick': {
					fn: function (grid, rowIndex, e){
							
							var userid = grid.getStore().getAt(rowIndex).get('UserId'); 

							if (userAdminWindows[0]) {
								Ext.destroy(userAdminWindows[0]);	
							}
	
							var ed = new Verbum.EditWindow({
								id: 'userEd',
								autoLoad: getMainUrl('action=user_admin&op=load&userid='+userid),
								url: getMainUrl('action=user_admin&op=save'),
								title: _('Editing...'),
					            width: 350,
					            height: 200,
					            iconCls: 'edit'
							});
							ed.show();
	
							ed.on({
								'success': function() {
									ds.reload();
								}
							});
							
							userAdminWindows[0] = ed.current;
        
    					}
				}				
			});
			
            ds.load();

        }
          
        win.show();
    },
    
    addReset: function() {
    	return {}
    },
    
	display : function(){
        this.createWindow();
	}
});